package com.shanyue.redwine.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.shanyue.redwine.BuildConfig;
import com.shanyue.redwine.R;
import com.shanyue.redwine.activity.ActivityMain;
import com.shanyue.redwine.utils.Constants;
import com.shanyue.redwine.utils.NotificationUtils;
import com.shanyue.redwine.utils.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateVersionService extends Service implements Runnable {
    public static final String ACTION_UPDATE_VERSION = UpdateVersionService.class
            .getCanonicalName().toLowerCase();
    private NotificationUtils mNotificationUtils;
    private Notification downLoadNotification;
    private NotificationManager notificationManager;
    private String downLoadUrl;
    public static boolean isStart = false;
    public static final String APP_NAME = "app.apk";
    public static final int FLAG_PROGRESS = 0, FLAG_FINISHED = 1, FLAG_ERROR = 3;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FLAG_PROGRESS:
                    isStart = true;
                    downLoadNotification.contentView.setTextViewText(R.id.tv_progress, msg.arg1 +
                            "%");
                    downLoadNotification.contentView.setProgressBar(R.id.pb_progress, 100, msg
                            .arg1, false);
                    notificationManager.notify(0, downLoadNotification);
                    break;
                case FLAG_FINISHED:
                    notificationManager.cancel(0);
                    Intent updateIntent = new Intent(Intent.ACTION_VIEW);
                    File file = new File(Constants.DIR_ROOT + "/" + APP_NAME);
                    String type = "application/vnd.android.package-archive";
                    updateIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),
                                BuildConfig.APPLICATION_ID + ".provider", file);
                        updateIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        updateIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        updateIntent.setDataAndType(contentUri, type);
                    } else {
                        updateIntent.setDataAndType(Uri.fromFile(file), type);
                    }
                    startActivity(updateIntent);
                    stopSelf();
                    break;
                case FLAG_ERROR:
                    isStart = false;
                    notificationManager.cancel(0);
                    Utils.showToast(getApplicationContext(), "新版本下载失败");
                    stopSelf();
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle bundle = intent != null ? intent.getExtras() : null;
        if (bundle == null || !bundle.containsKey(Constants.KEY_DATA)) {
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }
        downLoadUrl = intent.getStringExtra(Constants.KEY_DATA);
        if (TextUtils.isEmpty(downLoadUrl)) {
            Toast.makeText(getApplicationContext(), "下载地址出错", Toast.LENGTH_SHORT).show();
            return super.onStartCommand(intent, flags, startId);
        }
        notificationManager = (NotificationManager) getApplicationContext().getSystemService
                (Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= 26) {
            mNotificationUtils = new NotificationUtils(this);
            Notification.Builder builder = mNotificationUtils.getAndroidChannelNotification
                    (getString(R.string.app_name), "正在后台运行");
            downLoadNotification = builder.build();
        } else {
            //获取一个Notification构造器
            Notification.Builder builder = new Notification.Builder(getApplicationContext());
            Intent nfIntent = new Intent(getApplicationContext(), ActivityMain.class);
            builder.setContentIntent(PendingIntent.
                    getActivity(getApplicationContext(), 0, nfIntent, 0)) // 设置PendingIntent
                    .setContentTitle(getString(R.string.app_name)) // 设置下拉列表里的标题
                    .setSmallIcon(R.mipmap.ic_launcher_round) // 设置状态栏内的小图标
                    .setContentText("正在后台运行") // 设置上下文内容
                    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

            downLoadNotification = builder.build(); // 获取构建好的Notification
        }
        downLoadNotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音

//        downLoadNotification = new Notification();
        downLoadNotification.icon = R.mipmap.ic_launcher_round;
        downLoadNotification.tickerText = "开始更新";
        downLoadNotification.flags = Notification.DEFAULT_SOUND;
        downLoadNotification.flags = Notification.FLAG_SHOW_LIGHTS;
        downLoadNotification.flags = Notification.FLAG_NO_CLEAR;
        downLoadNotification.flags = Notification.FLAG_LOCAL_ONLY;
        downLoadNotification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
        downLoadNotification.contentView = new RemoteViews(getPackageName(), R.layout
                .view_notification_updateversion);
        downLoadNotification.contentView.setTextViewText(R.id.tv_name, getString(R.string
                .app_name) + " 新版本下载中...");
        new Thread(this).start();
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
    }

    @Override
    public void run() {
        try {
            URL url = new URL(downLoadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Charser", "GBK,utf-8;q=0.7,*;q=0.3");
            conn.setRequestProperty("Referer", url.toString());
            InputStream inputStream = conn.getInputStream();
            File file = new File(Constants.DIR_ROOT + "/" + APP_NAME);
            long length = conn.getContentLength();
            FileOutputStream outputStream = new FileOutputStream(file);
            notificationManager.notify(0, downLoadNotification);
            byte[] buffer = new byte[1024];
            long downLoadSize = 0;
            int currentSize;
            long lastUpdateTime = System.currentTimeMillis();
            while ((currentSize = inputStream.read(buffer)) > 0) {
                downLoadSize += currentSize;
                long currentUpdateTime = System.currentTimeMillis();
                if (currentUpdateTime - lastUpdateTime > 100) {
                    Message msg = new Message();
                    msg.what = FLAG_PROGRESS;
                    msg.arg1 = (int) (((float) downLoadSize / length) * 100);
                    handler.sendMessage(msg);
                    lastUpdateTime = currentUpdateTime;
                }
                outputStream.write(buffer, 0, currentSize);
            }

            outputStream.flush();
            inputStream.close();
            outputStream.close();
            conn.disconnect();
            handler.sendEmptyMessage(FLAG_FINISHED);
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(FLAG_ERROR);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
